package cn.edu.stu.syllabus.switcher;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import cn.edu.stu.syllabus.application.SyllabusApplication;
import cn.edu.stu.syllabus.datas.ThemeStyle;

/**
 * Created by daidaijie on 2016/12/31.
 */

public class ThemeStyleSwitcher {

    private static final String TAG = "ThemeStyleSwitcher";

    private static final String EXTRA_THEME_STYLE = "themeStyle";

    private SharedPreferences mSharedPreferences;

    private SharedPreferences.Editor mEditor;

    private ThemeStyle mThemeStyle;

    public int currentColorPrimary;
    public int currentColorPrimaryLight;

    private ThemeStyleSwitcher() {
        mSharedPreferences = SyllabusApplication.getContext()
                .getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        mThemeStyle = getThemeStyle();
        currentColorPrimary = mThemeStyle.colorPrimary;
        currentColorPrimaryLight = mThemeStyle.colorPrimaryLight;
    }

    private static class ThemeStyleSwitcherHolder {
        private static ThemeStyleSwitcher sInstance = new ThemeStyleSwitcher();
    }

    public static ThemeStyleSwitcher getInstance() {
        return ThemeStyleSwitcherHolder.sInstance;
    }

    public void setThemeStyle(String themeStyleName) {
        if (TextUtils.isEmpty(themeStyleName)
                || ThemeStyle.ThemeStylesHolder.sThemeStylesMap.get(themeStyleName) == null) {
            themeStyleName = ThemeStyle.ThemeStylesHolder.sThemeStyles.get(0).name;
        }
        mThemeStyle = ThemeStyle.ThemeStylesHolder.sThemeStylesMap.get(themeStyleName);

        mEditor.putString(EXTRA_THEME_STYLE, themeStyleName);
        mEditor.commit();
    }

    private ThemeStyle getThemeStyle() {
        String themeStyleName = mSharedPreferences.getString(EXTRA_THEME_STYLE, "");
        if (TextUtils.isEmpty(themeStyleName)) {
            themeStyleName = ThemeStyle.ThemeStylesHolder.sThemeStyles.get(0).name;
        }
        return ThemeStyle.ThemeStylesHolder.sThemeStylesMap.get(themeStyleName);
    }

    public ThemeStyle getCurrentThemeStyle() {
        return mThemeStyle;
    }

    public void switchThemeStyle(AppCompatActivity appCompatActivity) {
        Intent intent = new Intent(appCompatActivity, appCompatActivity.getClass());
        appCompatActivity.startActivity(intent);
        appCompatActivity.finish();
        appCompatActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

}
